<template>  <div class="dashboard-container">
    <!-- 操作区 -->
    <div class="dashboard-header">
      <div class="dashboard-title">仪表盘概览</div>
      <div class="dashboard-actions">
        <el-button type="primary" size="small" @click="loadDashboardData">
          <el-icon><Refresh /></el-icon>
          <span>刷新数据</span>
        </el-button>
      </div>
    </div>
    
    <!-- 顶部数据卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-item">
            <div class="card-icon" style="background-color: rgba(24, 144, 255, 0.1)">
              <el-icon :size="24" color="#1890ff"><Monitor /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-title">总设备数</div>
              <div class="card-number">{{ dashboardData.deviceCount }}</div>
              <div class="card-footer">
                <span class="card-compare">
                  <el-icon :size="12" color="#52c41a"><CaretTop /></el-icon>
                  <span>较昨日 +5%</span>
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-item">
            <div class="card-icon" style="background-color: rgba(82, 196, 26, 0.1)">
              <el-icon :size="24" color="#52c41a"><Check /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-title">在线设备</div>
              <div class="card-number">{{ dashboardData.onlineCount }}</div>
              <div class="card-footer">
                <span class="card-compare">
                  <span>在线率 {{ dashboardData.onlineRate }}</span>
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-item">
            <div class="card-icon" style="background-color: rgba(250, 173, 20, 0.1)">
              <el-icon :size="24" color="#faad14"><Warning /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-title">告警总数</div>
              <div class="card-number">{{ dashboardData.alarmCount }}</div>
              <div class="card-footer">
                <span class="card-compare">
                  <span :class="dashboardData.alarmTrend > 0 ? 'trend-up' : 'trend-down'">
                    <el-icon :size="12">
                      <component :is="dashboardData.alarmTrend > 0 ? 'CaretTop' : 'CaretBottom'" />
                    </el-icon>
                    <span>较昨日 {{ dashboardData.alarmTrend > 0 ? '+' : '' }}{{ dashboardData.alarmTrend }}%</span>
                  </span>
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-item">
            <div class="card-icon" style="background-color: rgba(245, 34, 45, 0.1)">
              <el-icon :size="24" color="#f5222d"><CircleCloseFilled /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-title">异常设备</div>
              <div class="card-number">{{ dashboardData.errorCount }}</div>
              <div class="card-footer">
                <span class="card-compare">
                  <span :class="dashboardData.errorTrend > 0 ? 'trend-up' : 'trend-down'">
                    <el-icon :size="12">
                      <component :is="dashboardData.errorTrend > 0 ? 'CaretTop' : 'CaretBottom'" />
                    </el-icon>
                    <span>较昨日 {{ dashboardData.errorTrend > 0 ? '+' : '' }}{{ dashboardData.errorTrend }}%</span>
                  </span>
                </span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="card-item">
            <div class="card-icon" style="background-color: rgba(24, 144, 255, 0.1)">
              <el-icon :size="24" color="#1890ff"><Monitor /></el-icon>
            </div>
            <div class="card-content">
              <div class="card-title">总用户数</div>
              <div class="card-number">{{ dashboardData.userCount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
      <!-- 主要内容区域 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 左侧内容区 -->
      <el-col :span="14">
        <!-- 设备使用统计 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>设备使用统计</span>
              <div class="header-right">
                <el-select v-model="chartTimeRange" placeholder="选择时间范围" size="small">
                  <el-option label="今日" value="today"></el-option>
                  <el-option label="本周" value="week"></el-option>
                  <el-option label="本月" value="month"></el-option>
                  <el-option label="全年" value="year"></el-option>
                </el-select>
              </div>
            </div>          </template>
          <el-table :data="displayedDeviceUsageData" style="width: 100%" stripe border height="350">
            <el-table-column prop="deviceName" label="设备名称" width="100"></el-table-column>
            <el-table-column prop="usageTime" label="使用时长" width="90">
              <template #default="scope">
                {{ scope.row.usageTime }}小时
              </template>
            </el-table-column>
            <el-table-column prop="batteryLevel" label="电量" width="80">
              <template #default="scope">
                <el-progress 
                  :percentage="scope.row.batteryLevel" 
                  :stroke-width="6" 
                  :text-inside="true" 
                  :status="getBatteryStatus(scope.row.batteryLevel)"
                ></el-progress>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="80">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)" size="small">{{ scope.row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="lastActive" label="最后活动" width="150"></el-table-column>
          </el-table>
          <div style="text-align: center; margin-top: 15px;">
            <el-pagination
              background
              layout="prev, pager, next"
              :total="deviceUsageData.length"
              :page-size="devicePageSize"
              @current-change="handleDevicePageChange"
              :current-page="deviceCurrentPage"
            ></el-pagination>
          </div>
        </el-card>
        
        <!-- 近期活动 -->
        <el-card class="activity-card" style="margin-top: 20px">
          <template #header>
            <div class="card-header">
              <span>近期活动</span>
            </div>
          </template>          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in recentActivities"
              :key="index"
              :timestamp="activity.timestamp"
              :type="index % 3 === 0 ? 'primary' : index % 3 === 1 ? 'success' : 'warning'"
            >
              {{ activity.description }}
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
      
      <!-- 右侧内容区 -->
      <el-col :span="10">
        <!-- 告警分布 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>告警分布</span>
            </div>
          </template>
          <div ref="pieChartRef" style="height: 350px"></div>
        </el-card>
          <!-- 设备电量 -->
        <el-card class="battery-card" style="margin-top: 20px">
          <template #header>
            <div class="card-header">
              <span>设备电量</span>
            </div>
          </template>          <div class="battery-list">
            <div v-for="(device, index) in displayedBatteryDevices" :key="index" class="battery-item">
              <span class="device-name">{{ device.name }}</span>
              <el-progress
                :percentage="device.battery"
                :status="getBatteryStatus(device.battery)"
                :stroke-width="10"
                :text-inside="true"
                :format="percentage => `${percentage}%`"
                style="flex-grow: 1; margin: 0 10px"
              ></el-progress>
              <span class="battery-value">{{ device.battery }}%</span>
            </div>
            <div style="text-align: center; margin-top: 15px;">
              <el-pagination
                background
                layout="prev, pager, next"
                :total="dashboardData.devices.length"
                :page-size="batteryPageSize"
                @current-change="handleBatteryPageChange"
                :current-page="batteryCurrentPage"
              ></el-pagination>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts/core';
import { PieChart } from 'echarts/charts';
import { TooltipComponent, LegendComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { ElMessage } from 'element-plus';
import { Refresh, Monitor, Check, Warning, CircleCloseFilled, CaretTop, CaretBottom } from '@element-plus/icons-vue';

// 导入混合API
import { 
  getDashboardOverview, 
  getDashboardAlerts,
  getDeviceStatusDistribution
} from '../../api/dashboardHybrid';

// 导入备用数据
import { 
  dashboardOverview, 
  recentActivities as mockActivities, 
  deviceUsage as mockDeviceUsage, 
  alertDistribution as mockAlertData
} from '../../api/mockData.fixed';

// 导入混合API工具
import { isMockData } from '../../api/hybridApi';

// 注册必要的ECharts组件
echarts.use([TooltipComponent, LegendComponent, GridComponent, PieChart, CanvasRenderer]);

let pieChart = null;

export default {
  name: 'DashboardView', /* eslint-disable-line vue/multi-word-component-names */
  components: {
    Refresh,
    Monitor,
    Check,
    Warning,
    CircleCloseFilled,
    CaretTop,
    CaretBottom
  },setup() {
    // 仪表盘数据
    const dashboardData = ref({
      deviceCount: 0,
      onlineCount: 0,
      onlineRate: '0%',
      alarmCount: 0,
      errorCount: 0,
      alarmTrend: 0,
      errorTrend: 0,
      userCount: 0,
      todayAlarmCount: 0,
      devices: []
    });
    
    // 图表显示的时间范围
    const chartTimeRange = ref('today');
    
    // 图表引用
    const pieChartRef = ref(null);    // 设备使用数据
    const deviceUsageData = ref([]);
      // 控制是否显示全部设备
    const showAllDevices = ref(false);
      // 设备使用统计分页相关变量
    const deviceCurrentPage = ref(1);
    const devicePageSize = ref(5);
    
    // 设备电池分页相关变量
    const batteryCurrentPage = ref(1);
    const batteryPageSize = ref(5);
    const displayedBatteryDevices = ref([]);
      // 控制是否显示更多电池设备 (已被分页机制取代，保留变量以兼容旧代码)
    const showMoreBatteryDevices = ref(false);
    
    // 要显示的设备数据
    const displayedDeviceUsageData = ref([]);
    
    // 近期活动
    const recentActivities = ref([]);
    
    // 初始化饼图
    const initPieChart = async () => {
      if (!pieChartRef.value) return;
        try {
        // 清除现有图表
        if (pieChart) {
          pieChart.dispose();
        }
        
        // 获取告警数据
        let alertData;
        try {
          // 尝试从API获取
          const alertResponse = await getDashboardAlerts();
          console.log('告警数据响应结果:', alertResponse);
          
          // 提取告警数据，适应不同的数据结构
          if (alertResponse.data && alertResponse.data.alertData) {
            // 新格式 - dashboardAlerts
            alertData = alertResponse.data.alertData;
          } else if (Array.isArray(alertResponse.data)) {
            // 旧格式 - 直接是数组
            alertData = alertResponse.data;          } else {
            // 回退到备用数据
            alertData = mockAlertData;
          }
          
          // 也可以从响应中直接获取告警数量
          if (alertResponse.data && alertResponse.data.todayAlertCount) {
            dashboardData.value.todayAlarmCount = alertResponse.data.todayAlertCount;
          }
        } catch (error) {          console.error('获取告警数据失败:', error);
          // 使用备用数据
          alertData = mockAlertData;
        }
        
        // 更新饼图
        if (alertData && alertData.length > 0) {
          // 计算今日告警总数（如果前面没有直接获取到）
          if (!dashboardData.value.todayAlarmCount) {
            const todayAlarms = alertData.reduce((sum, item) => sum + (item.value || 0), 0);
            dashboardData.value.todayAlarmCount = todayAlarms;
          }
            // 初始化饼图
          pieChart = echarts.init(pieChartRef.value);          const option = {            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
              orient: 'horizontal',
              bottom: '0%',
              left: 'center',
              itemWidth: 10,
              itemHeight: 10,
              textStyle: {
                fontSize: 12
              },
              data: alertData.map(item => item.name)
            },
            color: [
              '#5470c6', '#91cc75', '#fac858', '#ee6666', 
              '#73c0de', '#3ba272', '#fc8452', '#9a60b4', 
              '#ea7ccc', '#a5e7f0'
            ],            series: [
              {
                name: '告警分布',
                type: 'pie',
                radius: ['40%', '65%'],
                center: ['50%', '45%'],
                avoidLabelOverlap: true,
                itemStyle: {
                  borderRadius: 5,
                  borderWidth: 2,
                  borderColor: '#fff'
                },
                label: {
                  show: false,
                  position: 'center'
                },
                labelLine: {
                  show: false
                },
                data: alertData,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          };
          
          pieChart.setOption(option);
        } else {
          dashboardData.value.todayAlarmCount = 0;
        }
      } catch (error) {
        ElMessage.error('加载告警分布数据失败');
      }
    };    // 应用备用数据
    const applyMockData = () => {
      // 使用深拷贝直接设置备用数据
      dashboardData.value = JSON.parse(JSON.stringify(dashboardOverview));
      deviceUsageData.value = JSON.parse(JSON.stringify(mockDeviceUsage));
      recentActivities.value = JSON.parse(JSON.stringify(mockActivities));
      
      // 初始化分页数据显示
      updateDisplayedDevices();
      updateDisplayedBatteryDevices();
      
      // 重新初始化饼图
      initPieChart();
    };
      // 加载仪表盘数据
    const loadDashboardData = async () => {
      try {        // 使用混合API获取仪表盘概览数据
        const response = await getDashboardOverview();
          // 如果是模拟数据，会标记__isMockData属性
        if (isMockData(response)) {
          // 检查是否存在CORS错误
          const lastCorsError = localStorage.getItem('lastCorsError');
          if (lastCorsError) {
            try {
              const corsError = JSON.parse(lastCorsError);
              // 如果错误是最近5分钟内发生的
              const errorTime = new Date(corsError.timestamp);
              const now = new Date();
              const diffMinutes = (now - errorTime) / (1000 * 60);
                if (diffMinutes < 5) {
                ElMessage.warning({
                  message: '检测到跨域访问限制，正在使用本地备用数据',
                  duration: 5000
                });
                // 清除错误，避免重复提示
                localStorage.removeItem('lastCorsError');
              }
            } catch (e) {
              // 解析错误不做处理
              localStorage.removeItem('lastCorsError');
            }
          }
        }          // 更新仪表板顶部卡片数据
        dashboardData.value = response.data || dashboardOverview;
          // 加载告警数据和最近活动
        try {
          const alertsResponse = await getDashboardAlerts();
          // 兼容新旧数据结构
          if (alertsResponse.data && alertsResponse.data.recentActivities) {
            recentActivities.value = alertsResponse.data.recentActivities;
          } else if (Array.isArray(alertsResponse.data)) {
            // 如果直接返回数组（旧结构）
            recentActivities.value = alertsResponse.data;          } else {
            // 回退到备用数据
            recentActivities.value = mockActivities;
          }
        } catch (alertError) {
          console.error('加载告警数据失败:', alertError);          recentActivities.value = mockActivities;
        }
        
        // 加载设备状态分布
        try {
          const deviceStatusResponse = await getDeviceStatusDistribution();
          // 兼容新旧数据结构
          if (deviceStatusResponse.data && deviceStatusResponse.data.deviceUsage) {
            deviceUsageData.value = deviceStatusResponse.data.deviceUsage;
          } else if (Array.isArray(deviceStatusResponse.data)) {
            // 如果直接返回数组（旧结构）
            deviceUsageData.value = deviceStatusResponse.data;          } else {
            // 回退到备用数据
            deviceUsageData.value = mockDeviceUsage;
          }
        } catch (deviceError) {          console.error('加载设备状态分布失败:', deviceError);
          deviceUsageData.value = mockDeviceUsage;
        }
        
        // 更新电池状态设备
        updateDisplayedDevices();
        updateDisplayedBatteryDevices();

        // 初始化图表
        initPieChart();
      } catch (error) {
        console.error('加载仪表盘数据失败:', error);
        ElMessage.warning('加载仪表盘数据失败，已自动切换到备用数据模式');
          // 出错时回退到备用数据
        applyMockData();
      }
    };
    
    // 更新要显示的设备列表 - 使用分页方式
    const updateDisplayedDevices = () => {
      const startIndex = (deviceCurrentPage.value - 1) * devicePageSize.value;
      const endIndex = startIndex + devicePageSize.value;
      // 根据当前页码和每页显示数量计算设备列表
      displayedDeviceUsageData.value = deviceUsageData.value.slice(startIndex, endIndex);
    };
      
    // 处理设备分页变化
    const handleDevicePageChange = (newPage) => {
      deviceCurrentPage.value = newPage;
      updateDisplayedDevices();
    };
      // 切换设备显示数量 (不再使用此函数，保留以便兼容旧代码)
    const toggleDeviceDisplay = () => {
      showAllDevices.value = !showAllDevices.value;
      updateDisplayedDevices();
    };
      // 更新电池设备显示列表 - 使用分页方式
    const updateDisplayedBatteryDevices = () => {
      const startIndex = (batteryCurrentPage.value - 1) * batteryPageSize.value;
      const endIndex = startIndex + batteryPageSize.value;
      // 根据当前页码和每页显示数量计算电池设备列表
      displayedBatteryDevices.value = dashboardData.value.devices.slice(startIndex, endIndex);
    };
    
    // 处理电池设备分页变化
    const handleBatteryPageChange = (newPage) => {
      batteryCurrentPage.value = newPage;
      updateDisplayedBatteryDevices();
    };
      // 切换电池设备显示数量 (不再使用此函数，保留以便兼容旧代码)
    const toggleBatteryDevicesDisplay = () => {
      showMoreBatteryDevices.value = !showMoreBatteryDevices.value;
    };
    
    // 刷新页面功能
    const forceReload = () => {
      setTimeout(() => window.location.reload(true), 500);
    };    // 电池状态函数（返回值为Element Plus组件预定义状态）
    const getBatteryStatus = (percentage) => {
      if (percentage < 20) return 'exception'; // 危险状态
      if (percentage < 50) return 'warning';   // 警告状态
      return 'success';                        // 正常状态
    };
    
    // 状态类型函数
    const getStatusType = (status) => {
      if (status === '正常') return 'success';
      if (status === '警告' || status === '电量低') return 'warning';
      if (status === '错误' || status === '告警') return 'danger';
      return 'info';
    };
      // 确保使用备用数据
    localStorage.setItem('useMockData', 'true');
    
    // 备用数据状态
    const useMockData = ref(true);
      // 页面加载时初始化数据
    onMounted(() => {
      // 添加调试日志      console.log('仪表盘组件已挂载');
      console.log('正在加载仪表盘数据...');
      
      // 使用混合API加载数据
      loadDashboardData();
      
      // 监听窗口大小变化以调整图表大小
      window.addEventListener('resize', resizeCharts);
    });
    
    // 在组件销毁前清理图表和事件监听
    onBeforeUnmount(() => {
      if (pieChart) {
        pieChart.dispose();
      }
      window.removeEventListener('resize', resizeCharts);
    });
    
    // 调整图表大小
    const resizeCharts = () => {
      if (pieChart) {
        pieChart.resize();
      }
    };
    
    // 监听时间范围变化
    watch(chartTimeRange, () => {
      initPieChart();
    });      return {
      dashboardData,
      chartTimeRange,
      pieChartRef,
      deviceUsageData,
      displayedDeviceUsageData,
      displayedBatteryDevices,
      recentActivities,
      showAllDevices,
      showMoreBatteryDevices,
      deviceCurrentPage,
      devicePageSize,
      batteryCurrentPage,
      batteryPageSize,
      initPieChart,
      getBatteryStatus,
      getStatusType,
      toggleDeviceDisplay,
      toggleBatteryDevicesDisplay,
      handleDevicePageChange,
      handleBatteryPageChange,
      loadDashboardData,
      // 仅保留必要的功能
      useMockData,
      forceReload
    };
  }
};
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dashboard-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.dashboard-actions {
  display: flex;
  gap: 10px;
}

.data-card {
  height: 120px;
  margin-bottom: 20px;
}

.card-item {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 15px;
}

.card-content {
  flex-grow: 1;
}

.card-title {
  font-size: 14px;
  color: #999;
  margin-bottom: 10px;
}

.card-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.card-footer {
  font-size: 12px;
  color: #999;
}

.trend-up {
  color: #f5222d;
}

.trend-down {
  color: #52c41a;
}

.chart-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.battery-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.battery-item {
  display: flex;
  align-items: center;  margin-bottom: 12px;
}

.device-name {
  width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.battery-value {
  width: 50px;
  text-align: right;
  font-weight: bold;
}
</style>
